import {Injectable, EventEmitter} from '@angular/core';
import {UserModel} from "../model/user.model";
import {LocalStorage} from "../app.local-storage";
import {Subject} from "rxjs/Rx";
import {ROUTE} from "./route.service";
import {WfToast} from "../utils/toast.utils";

@Injectable()
export class USER {
  goLogin: EventEmitter<boolean> = new EventEmitter();
  refreshUser:EventEmitter<boolean> = new EventEmitter();
  refreshContract:EventEmitter<any> = new EventEmitter();


  private user:UserModel;
  private loginSuccess: Subject<UserModel> = new Subject<UserModel>();



  constructor(private ls:LocalStorage,private ROUTE:ROUTE,private toast:WfToast) {
    this.user = this.ls.getObject('user') as UserModel;
  }


  public update(user:UserModel){
    this.user = user;
    this.ls.setObject('user',user);
    this.refresh();
  }
  public getToken():string{
    this.user = this.ls.getObject('user') as UserModel;
    return this.user?this.user.token:'';
  }
  public setToken(token:string){
    this.user.token = token;
    this.update(this.user);
  }
  public get():UserModel{
      this.user = this.ls.getObject('user') as UserModel;
      return this.user;
  }
  public reset(){
    this.ls.setObject('user',null);
  }

  public isAuthenticated(): boolean {
    return this.get().token != undefined;
  }


  public needName(): boolean {
    return this.get().name !=undefined
  }
  public relogin():void {
    this.toast.error("您太久没有操作页面,请重新登录");
    this.goLogin.emit(true);
  }
  public refresh():void{
    this.refreshUser.emit(true);
  }
  public refreshC(v:any):void{
    this.refreshContract.emit(v);
  }


}
